package com.icesoft.system.safe.filter.impl;

import com.icesoft.framework.core.config.Cons;
import com.icesoft.framework.core.util.ResponseUtils;
import com.icesoft.framework.core.vo.JsonResult;
import com.icesoft.system.safe.filter.HeadSafeRequestFilter;
import com.icesoft.system.safe.filter.ParamSafeRequestFilter;
import com.icesoft.system.safe.service.CryptoKeyPairRepository;
import com.icesoft.system.safe.service.SafeRequestCryptoService;
import com.icesoft.system.safe.utils.SignUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.TreeMap;

@Slf4j
@Component
@RequiredArgsConstructor
public class SignFilter implements ParamSafeRequestFilter, HeadSafeRequestFilter {

	private final SafeRequestCryptoService safeRequestCryptoService;

	private final CryptoKeyPairRepository cryptoKeyPairRepository;

	@Override
	public boolean paramFilter(HttpServletRequest request, HttpServletResponse response,
							   TreeMap<String, String> paramMap) {
		String paramSign = safeRequestCryptoService.getSign();
		log.trace("head sign:{}", paramSign);
		if (StringUtils.isBlank(paramSign)) {
			ResponseUtils.writeJson(response, JsonResult.FAIL_AUTHENTICATION("签名sign为空"));
			return false;
		}
		String sign = SignUtil.sign(paramMap, TimeUnitNonceStrFilter.getTimeUnit(request), TimeUnitNonceStrFilter.getNonceStr(request));
		if (!paramSign.equalsIgnoreCase(sign)) {
			log.info("签名错误，服务器签名：{}，客户端签名：{}", sign, paramSign);
			ResponseUtils.writeJson(response, JsonResult.FAIL_EXCEPTION("签名错误"));
			return false;
		}
		return true;
	}


	@Override
	public boolean headFilter(HttpServletRequest request, HttpServletResponse response) {
		String sign = request.getHeader(Cons.HEAD_SIGN_PARAM_NAME);
		if (sign == null) {
			ResponseUtils.writeJson(response, JsonResult.FAIL_AUTHENTICATION("签名sign为空"));
			return false;
		}
		String keyId = request.getHeader(Cons.HEAD_KEY_ID_PARAM_NAME);
		if (keyId == null) {
			ResponseUtils.writeJson(response, JsonResult.FAIL_AUTHENTICATION("密钥id为空"));
			return false;
		}
		String privateKey = cryptoKeyPairRepository.findByKeyId(keyId).getPrivateKey();
		safeRequestCryptoService.decryptSign(privateKey, sign);
		return true;
	}
}
